package com.appspot.bs24event.controller.admin.event;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.util.BeanUtil;
import org.slim3.util.CopyOptions;

import com.appspot.bs24event.common.Constants;
import com.appspot.bs24event.meta.EventMeta;
import com.appspot.bs24event.model.Event;
import com.appspot.bs24event.service.EventService;

/**
 * EditController.
 * @version $Id: EditController.java 100 2011-06-17 03:14:57Z bs24event@gmail.com $
 */
public class EditController extends Controller {

    /** ログ */
    private static final Logger logger = Logger.getLogger(EditController.class.getName());

    private EventService service = new EventService();

    private EventMeta meta = EventMeta.get();

    @Override
    protected Navigation setUp() {
        logger.info(this.getClass().getName() + " start.");
        return super.setUp();
    }

    @Override
    protected void tearDown() {
        logger.info(this.getClass().getName() + " end.");
        super.tearDown();
    }

    @Override
    public Navigation run() throws Exception {
        // トークン作成
        HttpSession session = request.getSession();
        String token = session.getId() + "-" + System.currentTimeMillis();
        request.setAttribute(Constants.TOKEN_KEY, token);
        session.setAttribute(Constants.TOKEN_KEY, token);

        // 入力チェックエラーで戻ってきた場合
        if ( request.getAttribute("ERROR") != null ) {
            Event event = new Event();
            CopyOptions option = new CopyOptions();
            option.dateConverter("yyyy/mm/dd","eventDate");
            BeanUtil.copy(request, event, option);
            requestScope("event", event);
        }
        // 通常時
        else {
            // イベント詳細の取得
            Event event;
            try {
                event = service.get(asKey(meta.key), asLong(meta.version));
                requestScope("event", event);
            } catch (Exception e) {
                logger.warn("イベント詳細取得失敗",e);
                request.setAttribute("ERROR", "イベント詳細ページが開けませんでした。");
                return forward("/admin/event/list");
            }
        }

        // イベント修正画面へ遷移
        return forward("edit.jsp");
    }
}
